import { defineStore } from "pinia"
import router from "@/router/index"
import {
  accountLoginRequest,
  getUSerInfoById,
  getUSerManusByRoleId
} from "@/service/login/login"
import useMainStore from "@/stores/main/main"
import type { IAccount } from "@/types"
import { localCache } from "@/utils/cache"
import { mapMenusToRoutes,mapMenuToPermissions } from "@/utils/map-menus"
import type { RouteRecordRaw } from "vue-router"
const LOGIN_TOKEN = "login/token"
interface ILoginState {
  id: number
  name: string
  token: string
  userInfo: any
  userMenus: any
  permissions:string[]
}
const useLoginStroe = defineStore("login", {
  // 如何给state指定类型
  state: (): ILoginState => ({
    id: -1,
    name: "",
    token: "",
    userInfo: "",
    userMenus: "",
    permissions:[]
  }),
  actions: {
    async loginAccountAction(account: IAccount) {
      const loginResult = await accountLoginRequest(account)
      this.id = loginResult.data.id
      this.name = loginResult.data.name
      this.token = loginResult.data.token
      localCache.setCache(LOGIN_TOKEN, this.token)
      // 1获取登录用户的详细信息
      const userInfoResult = await getUSerInfoById(this.id)
      const userInfo = userInfoResult.data
      this.userInfo = userInfo
      // console.log(userInfoResult)
      localCache.setCache("userInfo", userInfo)

      //获取角色请求用户的权限
      const userMenuusResult = await getUSerManusByRoleId(userInfo.role.id)
      // console.log(userMenuusResult)
      const userMenus = userMenuusResult.data
      this.userMenus = userMenus
      localCache.setCache("userMenus", userMenus)

      //5、请求所有的role/department数据
      const mainStore = useMainStore()
      mainStore.fetchEntireDataAction()

      // 重要 获取登录用户的所有按钮权限
      const permissions=mapMenuToPermissions(userMenus)
      // console.log(permissions)
      this.permissions=permissions






      // 根据菜单动态的添加路由对象（独立的文件中）
      //1、获取菜单（useMenus）
      //2、动态获取所有的路由对象，放在数组中
      //路由对象都在独立的文件中
      //从文件中将所有路由对象先读取数组中
      //3、根据菜单去匹配正确的路由
      //router.addRoute('main',xxx)
      //动态添加路由
      // const localRoutes: RouteRecordRaw[] = []
      // //读取路由所有文件
      // const files: Record<string, any> = import.meta.glob(
      //   "../../router/main/**/*.ts",
      //   {
      //     eager: true
      //   }
      // )
      // for (const key in files) {
      //   const module = files[key]
      //   localRoutes.push(module.default)
      // }
      // //根据菜单匹配正确的路由
      // for (const menu of userMenus) {
      //   for (const submenu of menu.children) {
      //     const route = localRoutes.find((item) => item.path === submenu.url)
      //     console.log(route)
      //     if (route) {
      //       router.addRoute("main", route)
      //     }
      //   }
      // }
      const routes = mapMenusToRoutes(userMenus)
      // console.log(routes)
      routes.forEach((route) => {
        router.addRoute("main", route)
      })

      // console.log(files)
      // console.log(localRoutes)
      // localRoutes=files

      // 5.进行本地缓存
      //登录成功页面跳转
      router.push("/main")
    },
    loadLocalCacheAction() {
      const token = localCache.getCache(LOGIN_TOKEN)
      const userInfo = localCache.getCache("userInfo")
      const userMenus = localCache.getCache("userMenus")
      if (token && userInfo && userMenus) {
        this.token = token
        this.userInfo = userInfo
        this.userMenus = userMenus
        const mainStore = useMainStore()
        mainStore.fetchEntireDataAction()
        // 重要 获取登录用户的所有按钮权限
      const permissions=mapMenuToPermissions(userMenus)
      // console.log(permissions)
      this.permissions=permissions
      //
        const routes = mapMenusToRoutes(userMenus)
        routes.forEach((route) => {
          router.addRoute("main", route)
        })
      }
    }
  }
})
export default useLoginStroe
